<template>
    <div class="major-add">
        <el-form label-width="80px" ref="form" :model="form" :rules="rules">
            <el-form-item label="专业名" prop="name">
                <el-input v-model="form.name" placeholder="请输入专业名" />
            </el-form-item>

            <el-form-item label="系名" prop="departmentId">
                <el-select filterable v-model="form.departmentId" placeholder="请选择系">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end;">
            <el-button type="primary" @click="onsubmit">确定</el-button>
            <el-button type="primary" @click="handclose" plain>取消</el-button>
        </span>
    </div>
</template>
<script>
import { departmentnames, adminmajor, adminmajorid } from '@/api/major';
export default {
    props: {
        id: { type: Number, default: null }
    },
    data() {
        return {
            form: {
                name: '',
                departmentId: null
            },
            options: [],
            rules: {
                name: [
                    { required: true, message: '请输入专业名', trigger: 'blur' }
                ],
                departmentId: [
                    { required: true, message: '请选择系', trigger: 'change' }
                ]
            }
        }
    },
    mounted() {
        departmentnames().then(res => {
            console.log(res);
            this.options = (res.data || []).map(item => ({
                label: item.name,
                value: item.id
            }));
        })
        if (this.id) {
            adminmajorid(this.id).then(res => {
                if (res.code === 0) {
                    this.form = res.data;
                } else {
                    this.$message.error('获取专业信息失败');
                }
            });
        }
    },
    methods: {
        async onsubmit() {
            this.$refs["form"].validate(async flag => {
                if (flag) {
                    const res = await adminmajor(this.form);
                    if (res.code == 0) {
                        this.$message({
                            message: '操作成功',
                            type: 'success',
                        });
                        this.$emit('done');
                    } else {
                        console.log(res);
                        this.$message({
                            message: '操作失败',
                            type: 'error',
                        });
                    }

                }
            })
        },
        handclose() {
            this.$emit('close')
        }
    }
}
</script>
